<template>
  <div class="g-bd4 f-cb">
    <el-row class="tac">
      <el-col :span="4">
        <div class="playlist-menu">
          <el-menu

            class="el-menu-vertical-demo"
            background-color="#F8F8F8"
            text-color="#000000"
            active-text-color="#BD161C"
            @select="handleSelect">
            <el-submenu index="2">
              <template slot="title">
                <i class="el-icon-goods"></i>
                <span>创建的专辑</span>
              </template>
              <el-menu-item v-for="(item, index) in albumCreated" :index="item" class="playlist-menu-item">
                <img :src="changeUrlToResizeImg(item.picUrl, 30)"
                       height="30"
                       width="30"
                       class="item-playlist-cover">
                {{item.name}}
              </el-menu-item>
            </el-submenu>
            <el-submenu index="4">
              <template slot="title">
                <i class="el-icon-setting"></i>
                <span>专辑管理</span>
              </template>
              <el-menu-item index="add">
                添加专辑
              </el-menu-item>
              <el-menu-item index="addSong">
                为专辑添加歌曲
              </el-menu-item>
              <el-menu-item index="delete">
                删除专辑
              </el-menu-item>
            </el-submenu>
          </el-menu>
        </div>
      </el-col>
      <el-col :span="20">
        <div v-if="albumId !== ''">
          <div class="playlist-detail" v-if="!isNew && !isNewSong">
            <!--<song-sheet-detail v-if="hackReset" :playlistId="playlistId"></song-sheet-detail>-->
            <album-songs-detail v-if="hackReset" :albumId="albumId"></album-songs-detail>
          </div>
        </div>
        <div v-if="isNew">
          <div class="edit-playlist">

            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="专辑名" prop="name">
                <el-input v-model="ruleForm.name"></el-input>
              </el-form-item>
              <el-form-item label="介绍" prop="description">
                <el-input type="textarea" v-model="ruleForm.description"></el-input>
              </el-form-item>
              <el-form-item label="上传封面">
                <el-upload
                  v-loading="loading"
                  class="avatar-uploader"
                  :action="uploadCoverUrl"
                  :show-file-list="false"
                  :on-progress="handleProgress"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitAlbumForm">确定</el-button>
                <el-button @click="back()">取消</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div v-if="albumId !== '' && !isNew && isNewSong">
          <div class="edit-playlist">

            <el-form :model="songForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="歌名" prop="name">
                <el-input v-model="songForm.name"></el-input>
              </el-form-item>
              <el-form-item label="歌词" prop="lyric">
                <el-input type="textarea" v-model="songForm.lyric"></el-input>
              </el-form-item>
              <el-form-item label="上传歌曲">
                <el-upload id="elUpload"
                  class="upload-demo"
                  :action="uploadMP3Url"
                  :on-preview="handlePreview"
                  :before-upload="beforeSongUpload"
                  :on-remove="handleRemove"
                  :on-success="handleSongSuccess"
                  :before-remove="beforeRemove"
                  multiple
                  :limit="1"
                  :on-exceed="handleExceed"
                  :file-list="fileList">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传mp3文件，且不超过10M</div>
                </el-upload>

              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitNewSong">确定</el-button>
                <el-button @click="back()">取消</el-button>
              </el-form-item>
            </el-form>
          </div>

        </div>
      </el-col>
    </el-row>
    <audio id="songAudio" :src="songLocalUrl" v-show="false" @canplay="getDuration" @change="getDuration"></audio>
  </div>
</template>

<script>
  import {getUser} from "../util/userUtils"
  import {artistAlbumList, userCreatedPlaylists, userSubscribePlaylists, apiContext} from "../service/getData"

  import SongSheetDetail from '../components/songSheetDetail'
  import EditPlaylist from './editPlaylist'
  import AlbumSongsDetail from '../components/albumSongsDetail'
  export default {
    name: 'myAlbum',
    data() {
      return {
        songName: "",
        dialogSongNameVisible: false,
        uploadCoverUrl: "",
        uploadMP3Url: "",
        albumId: "",
        albumCreated: [],
        albumNow: {},
        user: {},
        hackReset: true,

        isNew: false,
        isNewSong: false,
        imageUrl: null,
        imageId: null,
        ruleForm: {
          name: null,
          description: null
        },
        rules: {
          name: [
            { required: true, message: '请输入名称', trigger: 'blur' },
            { min: 1, max: 20, message: '长度为 1~20 个字符', trigger: 'blur' }
          ],
          description: [
            { required: false, message: '请填写介绍', trigger: 'blur' }
          ]
        },
        loading: false,
        song: {},
        songAudio: {},
        duration: null,
        songLocalUrl: null,
        songForm: {name: "", lyric: ""}
      }
    },
    inject: ['reload'],
    methods: {
      submitNewSong() {
        let user = getUser();

        this.$http.post(apiContext+"song/add", {
          name: this.songForm.name,
          songUrlId: this.song.songUrlId,
          duration: this.duration,
          lyric: this.songForm.lyric,
          albumId: this.albumId
        }, {
          emulateJSON : true,
          headers: {
            'Content-Type': 'x-www-form-urlencoded',
            'userId': user.id,
            'userToken': user.userToken
          }}).then(res => {
          console.log(res);
          let status = res.body.status;
          if (status === 200) {
            this.$message({
              message: "添加成功",
              type: 'success'
            });
            this.back();
          } else {
            this.$message({
              message: res.body.msg,
              type: 'error'
            });
          }
        })
      },
      getDuration(e) {
        console.log(e)
        this.duration = parseInt(e.target.duration * 1000);
        // this.song['duration'] = this.duration;
        // console.log(this.song)
      },
      handleSongSuccess(res, file) {
        console.log(res);
        if (res.status === 200) {

          this.$message.success("上传成功");
          let data = res.data;
          this.song = {songUrlId: data.fileId, name: this.songName, url: data.filePath}
          console.log(this.song)
          this.songLocalUrl = URL.createObjectURL(file.raw);
          // let duration = this.songAudio.duration;
          // console.log(duration)
        } else {
          this.$message.error(res.msg);
        }
      },
      handlePreview(file) {

      },
      beforeSongUpload(file) {
        console.log(file);

        let name = file['name'];
        this.songName = name.split(".")[0];

        const isJPG = file.type === 'audio/mp3';
        const isLt2M = file.size / 1024 / 1024 < 10;

        if (!isJPG) {
          this.$message.error('上传图片只能是 MP3 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 10MB!');
        }

        return isJPG && isLt2M;

      },
      beforeRemove(file, fileList) {
        console.log(file)
        return true;
        // return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      changeUrlToResizeImg(picUrl, size) {
        return picUrl.replace(/yunmusic_dev/, "resize_" + size + 'x' + size);
      },
      back() {
        this.isNew = false;
        this.isNewSong = false;
      },
      submitAlbumForm() {
        let user = getUser();

        this.$http.post(apiContext+"album/publish", {
          name: this.ruleForm.name,
          description: this.ruleForm.description,
          artistId: this.user.artistId,
          picUrlId: this.imageId
        }, {
          emulateJSON : true,
          headers: {
            'Content-Type': 'x-www-form-urlencoded',
            'userId': user.id,
            'userToken': user.userToken
          }}).then(res => {
          console.log(res);
          let status = res.body.status;
          if (status === 200) {
            this.$message({
              message: "添加成功",
              type: 'success'
            });
            this.getArtistAlbums();
            this.back();
          } else {
            this.$message({
              message: res.body.msg,
              type: 'error'
            });
          }
        })
      },
      handleProgress(event, file, fileList) {
        this.loading = true;
      },
      handleAvatarSuccess(res, file) {
        console.log(res);
        this.loading = false;
        if (res.status === 200) {
          this.$message.success("上传成功");
          let data = res.data;
          this.imageUrl = data.filePath;
          // this.imageUrl = data.filePath;
          this.imageId = data.fileId;
        } else {
          this.$message.error(res.msg);
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      getArtistAlbums() {
        artistAlbumList(this).get({
          artistId: this.user.artistId,
          page: 1,
          pageSize: 1000
        }).then(res => {
          console.log(res);
          if (res.body.status === 200) {
            this.albumCreated = res.body.data.rows;
          }
        })
      },
      deletePlaylist() {
        this.$confirm('此操作将永久删除该专辑, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let userId = this.user.id;
          let userToken = this.user.userToken;
          this.$http.post(apiContext+"album/delete", {
            albumId: this.albumId,
          }, {
            emulateJSON : true,
            headers: {
              'Content-Type': 'x-www-form-urlencoded',
              'userId': userId,
              'userToken': userToken
            }}).then(res => {
            console.log(res);
            let status = res.body.status;
            if (status === 200) {
              this.$message({
                message: "删除成功",
                type: 'success'
              });
              // 刷新用户创建的歌单
              // this.getCreatedPlaylists();
              this.reload();
            } else {
              this.$message({
                message: res.body.msg,
                type: 'error'
              });
            }
          })

        }).catch(() => {

        });

      },
      handleSelect(key, keyPath) {
        console.log(keyPath);

        if (keyPath[0] === '4' && keyPath[1] === 'addSong') {
          this.isNewSong = true;
        } else {
          this.isNewSong = false;
        }

        if (keyPath[0] === '4' && keyPath[1] === 'edit') {
          this.isNew = true;
        } else {
          this.isNew = false;
        }
        if (keyPath[0] === '2') {
          console.log(key);
          this.albumId = key.id;
          this.albumNow = key;
          // 刷新歌单详情
          this.hackReset = false;
          this.$nextTick(() => {
            this.hackReset = true
          })
        } else if (keyPath[0] === '4') {
          if (keyPath[1] === 'addSong') {
            this.isNewSong = true;
          } else if (keyPath[1] === 'delete') {
            this.deletePlaylist();
          } else if (keyPath[1] === 'add') {
            this.isNew = true;
          }
        }

      },
      getArtistByUser() {

      },
    },

    mounted() {
      this.songAudio = document.getElementById('songAudio');
      console.log(this.songAudio)
      this.uploadCoverUrl = apiContext + "/upload/cover/album"
      this.uploadMP3Url = apiContext + "/upload/song"
      this.user = getUser();
      // this.getArtistByUser();
      this.getArtistAlbums();
    },
    components: {AlbumSongsDetail, EditPlaylist, SongSheetDetail}
  }
</script>

<style scoped>
  .g-bd, .g-bd1, .g-bd2, .g-bd3, .g-bd4, .g-bd5, .g-bd6, .g-bd7 {
    width: 980px;
    min-height: 700px;
    _height: 700px;
    margin: 0 auto;
    background-color: #fff;
    border: 1px solid #d3d3d3;
    border-width: 0 1px;
  }

  .g-bd4 {
    background: url(../image/wrap2.png) repeat-y center 0;
  }

  .f-cb:after {
    clear: both;
    content: '.';
    display: block;
    height: 0;
    visibility: hidden;
  }

  .playlist-detail {
    margin-left: 10px;
  }

  .playlist-menu {
    /*display: inline-block;*/
    margin-right: -18px;
  }

  .playlist-menu-item {
    /*display: inline;*/
    /*width: 200px;*/
    font-size: 10px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .playlist-menu-item-right {
    display: inline-block;
  }

  .playlist-name {
    font-size: 10px;
    /*overflow: hidden;*/
    /*white-space: nowrap;*/
    /*text-overflow: ellipsis;*/
  }

  .playlist-cover {
    display: inline;
  }

  .edit-playlist {
    margin-top: 30px;
    margin-right: 30px;
  }

  .avatar-uploader {
    width: 178px;
    height: 178px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
